import ReactDOM from "react-dom/client";
import { Spin } from "antd";

const Loading = ({ tip = "加载中" }: { tip?: string }) => {
	return <Spin tip={tip} size="large" className="request-loading" />;
};

const LoadingStyle = `
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 9998;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    background: rgb(0 0 0 / 50%);
`;

let needLoadingRequestCount = 0;

// * 显示loading
export const showFullScreenLoading = () => {
	if (needLoadingRequestCount === 0) {
		let dom = document.createElement("div");
		dom.setAttribute("id", "loading");
		dom.setAttribute("style", LoadingStyle);
		document.body.appendChild(dom);
		ReactDOM.createRoot(dom).render(<Loading />);
	}
	needLoadingRequestCount++;
};

// * 隐藏loading
export const tryHideFullScreenLoading = () => {
	if (needLoadingRequestCount <= 0) return;
	needLoadingRequestCount--;
	if (needLoadingRequestCount === 0) {
		document.body.removeChild(document.getElementById("loading") as HTMLElement);
	}
};
